/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.rocketmq.client.impl.consumer;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.ConsumeReturnType;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.consumer.store.OffsetStore;
import org.apache.rocketmq.client.hook.ConsumeMessageContext;
import org.apache.rocketmq.client.log.ClientLogger;
import org.apache.rocketmq.client.stat.ConsumerStatsManager;
import org.apache.rocketmq.common.MixAll;
import org.apache.rocketmq.common.ThreadFactoryImpl;
import org.apache.rocketmq.common.message.MessageAccessor;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.common.protocol.body.CMResult;
import org.apache.rocketmq.common.protocol.body.ConsumeMessageDirectlyResult;
import org.apache.rocketmq.common.utils.ThreadUtils;
import org.apache.rocketmq.logging.InternalLogger;
import org.apache.rocketmq.remoting.common.RemotingHelper;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ConsumeMessageConcurrentlyService implements ConsumeMessageService {
    private static final InternalLogger log = ClientLogger.getLog();
    private final DefaultMQPushConsumerImpl defaultMQPushConsumerImpl;
    private final DefaultMQPushConsumer defaultMQPushConsumer;
    /**
     * 消息监听器(并发模式)
     */
    private final MessageListenerConcurrently messageListener;
    /**
     * 消费线程池中的阻塞队列
     * <p>
     * note:无界队列,并且不可配置容量.....
     *  那 DefaultMQPushConsumer#consumeThreadMax 配置就毫无意义了.
     *  只能使用 DefaultMQPushConsumer#consumeThreadMin 来设置线程池中线程数量.
     */
    private final BlockingQueue<Runnable> consumeRequestQueue;
    /**
     * 消费线程池
     */
    private final ThreadPoolExecutor consumeExecutor;

    private final String consumerGroup;

    private final ScheduledExecutorService scheduledExecutorService;
    private final ScheduledExecutorService cleanExpireMsgExecutors;

    public ConsumeMessageConcurrentlyService(DefaultMQPushConsumerImpl defaultMQPushConsumerImpl, MessageListenerConcurrently messageListener) {
        this.defaultMQPushConsumerImpl = defaultMQPushConsumerImpl;
        this.messageListener = messageListener;

        this.defaultMQPushConsumer = this.defaultMQPushConsumerImpl.getDefaultMQPushConsumer();
        this.consumerGroup = this.defaultMQPushConsumer.getConsumerGroup();
        // 无界队列,并且不可配置容量.那 DefaultMQPushConsumer#consumeThreadMax 配置就毫无意义了.
        this.consumeRequestQueue = new LinkedBlockingQueue<Runnable>();

        this.consumeExecutor = new ThreadPoolExecutor(
            this.defaultMQPushConsumer.getConsumeThreadMin(), // 默认20
            this.defaultMQPushConsumer.getConsumeThreadMax(), // 默认64
            1000 * 60,
            TimeUnit.MILLISECONDS,
            this.consumeRequestQueue,
            new ThreadFactoryImpl("ConsumeMessageThread_"));

        this.scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(new ThreadFactoryImpl("ConsumeMessageScheduledThread_"));
        this.cleanExpireMsgExecutors = Executors.newSingleThreadScheduledExecutor(new ThreadFactoryImpl("CleanExpireMsgScheduledThread_"));
    }

    @Override
    public void start() {
        this.cleanExpireMsgExecutors.scheduleAtFixedRate(new Runnable() {

            @Override
            public void run() {
                cleanExpireMsg();
            }

        }, this.defaultMQPushConsumer.getConsumeTimeout(), this.defaultMQPushConsumer.getConsumeTimeout(), TimeUnit.MINUTES);
    }

    @Override
    public void shutdown(long awaitTerminateMillis) {
        this.scheduledExecutorService.shutdown();
        ThreadUtils.shutdownGracefully(this.consumeExecutor, awaitTerminateMillis, TimeUnit.MILLISECONDS);
        this.cleanExpireMsgExecutors.shutdown();
    }

    @Override
    public void updateCorePoolSize(int corePoolSize) {
        if (corePoolSize > 0
            && corePoolSize <= Short.MAX_VALUE
            && corePoolSize < this.defaultMQPushConsumer.getConsumeThreadMax()) {
            this.consumeExecutor.setCorePoolSize(corePoolSize);
        }
    }

    @Override
    public void incCorePoolSize() {

    }

    @Override
    public void decCorePoolSize() {

    }

    @Override
    public int getCorePoolSize() {
        return this.consumeExecutor.getCorePoolSize();
    }

    @Override
    public ConsumeMessageDirectlyResult consumeMessageDirectly(MessageExt msg, String brokerName) {
        ConsumeMessageDirectlyResult result = new ConsumeMessageDirectlyResult();
        result.setOrder(false);
        result.setAutoCommit(true);

        List<MessageExt> msgs = new ArrayList<MessageExt>();
        msgs.add(msg);
        MessageQueue mq = new MessageQueue();
        mq.setBrokerName(brokerName);
        mq.setTopic(msg.getTopic());
        mq.setQueueId(msg.getQueueId());

        ConsumeConcurrentlyContext context = new ConsumeConcurrentlyContext(mq);

        this.defaultMQPushConsumerImpl.resetRetryAndNamespace(msgs, this.consumerGroup);

        final long beginTime = System.currentTimeMillis();

        log.info("consumeMessageDirectly receive new message: {}", msg);

        try {
            // 消费消息
            ConsumeConcurrentlyStatus status = this.messageListener.consumeMessage(msgs, context);
            if (status != null) {
                switch (status) {
                    case CONSUME_SUCCESS:
                        result.setConsumeResult(CMResult.CR_SUCCESS);
                        break;
                    case RECONSUME_LATER:
                        result.setConsumeResult(CMResult.CR_LATER);
                        break;
                    default:
                        break;
                }
            } else {
                result.setConsumeResult(CMResult.CR_RETURN_NULL);
            }
        } catch (Throwable e) {
            result.setConsumeResult(CMResult.CR_THROW_EXCEPTION);
            result.setRemark(RemotingHelper.exceptionSimpleDesc(e));

            log.warn(String.format("consumeMessageDirectly exception: %s Group: %s Msgs: %s MQ: %s",
                                   RemotingHelper.exceptionSimpleDesc(e),
                                   consumerGroup,
                                   msgs,
                                   mq), e);
        }

        result.setSpentTimeMills(System.currentTimeMillis() - beginTime);

        log.info("consumeMessageDirectly Result: {}", result);

        return result;
    }

    /**
     * 提交消费请求
     * <pre>
     * 并发消费消息
     * - 每次最多消费消息数量: {@link DefaultMQPushConsumer#getConsumeMessageBatchMaxSize()}
     * - 每次把消费请求 {@link ConsumeRequest},提交到线程池 {@link #consumeExecutor}中.
     * </pre>
     *
     * @param msgs              消息
     * @param processQueue      consumer正在处理中的队列信息
     * @param messageQueue      消息队列
     * @param dispatchToConsume 是否把消息分配给消费者进行消费(并发消费时,这参数没有用到.只有顺序消费服务中才用到了 {@link ConsumeMessageOrderlyService#submitConsumeRequest})
     */
    @Override
    public void submitConsumeRequest(
            final List<MessageExt> msgs,
            final ProcessQueue processQueue,
            final MessageQueue messageQueue,
            final boolean dispatchToConsume) {

        // 每次批量消费多少条消息.   默认值:1
        final int consumeBatchSize = this.defaultMQPushConsumer.getConsumeMessageBatchMaxSize();
        if (msgs.size() <= consumeBatchSize) {
            ConsumeRequest consumeRequest = new ConsumeRequest(msgs, processQueue, messageQueue);
            try {
                // 向线程池中,提交消费请求   (一个消费请求中,最多包含consumeMessageBatchMaxSize个消息.默认:1)
                this.consumeExecutor.submit(consumeRequest);
            } catch (RejectedExecutionException e) {
                this.submitConsumeRequestLater(consumeRequest);
            }
        } else {
            // 消息数量超过 consumeMessageBatchMaxSize个消息(默认:1),则把消息,拆分成多个消费请求,然后再丢给线程池.
            for (int total = 0; total < msgs.size(); ) {
                List<MessageExt> msgThis = new ArrayList<MessageExt>(consumeBatchSize);
                for (int i = 0; i < consumeBatchSize; i++, total++) {
                    if (total < msgs.size()) {
                        msgThis.add(msgs.get(total));
                    } else {
                        break;
                    }
                }

                ConsumeRequest consumeRequest = new ConsumeRequest(msgThis, processQueue, messageQueue);
                try {
                    this.consumeExecutor.submit(consumeRequest);
                } catch (RejectedExecutionException e) {
                    for (; total < msgs.size(); total++) {
                        msgThis.add(msgs.get(total));
                    }
                    // 触发拒绝策略了:稍后提交消费请求
                    this.submitConsumeRequestLater(consumeRequest);
                }
            }
        }
    }


    /**
     * 清除过期消息(定时任务中调用)
     */
    private void cleanExpireMsg() {
        Set<Map.Entry<MessageQueue, ProcessQueue>> entries = this.defaultMQPushConsumerImpl.getRebalanceImpl().getProcessQueueTable().entrySet();
        for (Map.Entry<MessageQueue, ProcessQueue> next : entries) {
            ProcessQueue pq = next.getValue();
            pq.cleanExpiredMsg(this.defaultMQPushConsumer);
        }
    }

    /**
     * <pre>
     * 处理消费结果
     *
     * 主要三个步骤:
     * 1/ 消费状态管理器 —— 记录消费状态/统计信息等 (不是很重要)
     * 2/ 根据 消费模式 ,处理消费失败的mq消息.(保证了集群消费模式,消息不丢失.)
     * 3/ 处理消费成功的消息:修改消费成功的偏移量. {@link OffsetStore#updateOffset}
     *
     * </pre>
     *
     * @param status         消费状态
     * @param context        消费上下文
     * @param consumeRequest 消费请求(包含mq消息)
     */
    public void processConsumeResult(final ConsumeConcurrentlyStatus status,
                                     final ConsumeConcurrentlyContext context,
                                     final ConsumeRequest consumeRequest) {

        // 每次消费多个消息:consumeRequest.getMsgs() .如果前三个消费成功,则设置 ackIndex=2.
        // 但是一般来说,不会设置ackIndex.所以大多数情况都是 ackIndex = Integer.MAX_VALUE
        int ackIndex = context.getAckIndex();
        if (consumeRequest.getMsgs().isEmpty())
            return;

        ConsumerStatsManager consumerStatsManager = this.getConsumerStatsManager();
        // note:根据消费结果,计算ackIndex  并 记录消费状态(统计数据等)
        switch (status) {
            case CONSUME_SUCCESS:
                if (ackIndex >= consumeRequest.getMsgs().size()) {
                    ackIndex = consumeRequest.getMsgs().size() - 1;
                }
                int ok = ackIndex + 1;
                int failed = consumeRequest.getMsgs().size() - ok;
                consumerStatsManager.incConsumeOKTPS(consumerGroup, consumeRequest.getMessageQueue().getTopic(), ok);
                consumerStatsManager.incConsumeFailedTPS(consumerGroup, consumeRequest.getMessageQueue().getTopic(), failed);
                break;
            case RECONSUME_LATER:
                ackIndex = -1;
                consumerStatsManager.incConsumeFailedTPS(consumerGroup, consumeRequest.getMessageQueue().getTopic(), consumeRequest.getMsgs().size());
        }

        // note:根据 消费模式 ,处理消费失败的mq消息.(保证了集群消费模式,消息不丢失.)
        switch (this.defaultMQPushConsumer.getMessageModel()) {
            // 广播模式:只打印日志. (广播模式,如果消费失败,只打印warn日志.广播消费模式,不会重试消费.)
            case BROADCASTING:
                for (int i = ackIndex + 1; i < consumeRequest.getMsgs().size(); i++) {
                    MessageExt msg = consumeRequest.getMsgs().get(i);
                    log.warn("BROADCASTING, the message consume failed, drop it, {}", msg.toString());
                }
                break;
            // 集群模式:
            case CLUSTERING:
                // 消费失败的mq消息,并且重新发送给broker时,也失败的mq消息.
                List<MessageExt> msgBackFailed = new ArrayList<>(consumeRequest.getMsgs().size());
                // ackIndex 是消费成功的消息的下标.从ackIndex+1开始,都是消费失败的消息.
                for (int i = ackIndex + 1; i < consumeRequest.getMsgs().size(); i++) {
                    MessageExt msg = consumeRequest.getMsgs().get(i);
                    // note:把消费失败的消息,重新发送给broker.
                    boolean success = this.sendMessageBack(msg, context);
                    if (!success) {
                        // 消息重试次数+1
                        msg.setReconsumeTimes(msg.getReconsumeTimes() + 1);
                        msgBackFailed.add(msg);
                    }
                }
                // 消费失败 并且 重新发送给broker都失败的消息.则让此consumer在5秒后重新消费.
                if (!msgBackFailed.isEmpty()) {
                    // 移除消费失败的消息.(比如总共5个消息,2个消费失败.则把这两个消费失败的消息移除.)
                    consumeRequest.getMsgs().removeAll(msgBackFailed);
                    // 5秒后,提交消费请求
                    this.submitConsumeRequestLater(msgBackFailed, consumeRequest.getProcessQueue(), consumeRequest.getMessageQueue());
                }
        }

        // note:消费成功的消息:修改消费偏移量.
        long offset = consumeRequest.getProcessQueue().removeMessage(consumeRequest.getMsgs());
        if (offset >= 0 && !consumeRequest.getProcessQueue().isDropped()) {
            // note:修改消费成功的偏移量.
            this.defaultMQPushConsumerImpl.getOffsetStore().updateOffset(consumeRequest.getMessageQueue(), offset, true);
        }
    }

    public ConsumerStatsManager getConsumerStatsManager() {
        return this.defaultMQPushConsumerImpl.getConsumerStatsManager();
    }

    /**
     * 把消费失败的消息,重新发送给broker.
     *
     * @param msg     消费失败的消息
     * @param context 消费上下文
     * @return
     */
    public boolean sendMessageBack(final MessageExt msg, final ConsumeConcurrentlyContext context) {
        // 下一次消费时的延迟等级.
        int delayLevel = context.getDelayLevelWhenNextConsume();

        // Wrap topic with namespace before sending back message.
        msg.setTopic(this.defaultMQPushConsumer.withNamespace(msg.getTopic()));
        try {
            // 把消费失败的消息,重新发送给broker.      请求类型: RequestCode#CONSUMER_SEND_MSG_BACK
            this.defaultMQPushConsumerImpl.sendMessageBack(msg, delayLevel, context.getMessageQueue().getBrokerName());
            return true;
        } catch (Exception e) {
            log.error("sendMessageBack exception, group: " + this.consumerGroup + " msg: " + msg.toString(), e);
            return false;
        }
    }

    /**
     * 延迟5秒后,再把消费请求提交到消费线程池中.
     * @param msgs 需要消费的mq消息
     */
    private void submitConsumeRequestLater(List<MessageExt> msgs, ProcessQueue processQueue, MessageQueue messageQueue) {
        this.scheduledExecutorService.schedule(() -> submitConsumeRequest(msgs, processQueue, messageQueue, true),
                                               5000, TimeUnit.MILLISECONDS);
    }

    /**
     * 延迟5秒后,再把消费请求提交到消费线程池中.
     *
     * @param consumeRequest 消费请求
     */
    private void submitConsumeRequestLater(final ConsumeRequest consumeRequest) {
        this.scheduledExecutorService.schedule(() -> consumeExecutor.submit(consumeRequest), 5000, TimeUnit.MILLISECONDS);
    }

    /**
     * 消费请求.
     *
     * @see ConsumeRequest#run() 消费逻辑.
     */
    class ConsumeRequest implements Runnable {
        private final List<MessageExt> msgs;      // 消费请求需要处理的消息
        private final ProcessQueue processQueue;  // 此consumer正在处理中的队列(维护了当前运行状态等信息)
        private final MessageQueue messageQueue;  // 消息队列

        public ConsumeRequest(List<MessageExt> msgs, ProcessQueue processQueue, MessageQueue messageQueue) {
            this.msgs = msgs;
            this.processQueue = processQueue;
            this.messageQueue = messageQueue;
        }

        public List<MessageExt> getMsgs() {
            return msgs;
        }

        public ProcessQueue getProcessQueue() {
            return processQueue;
        }

        /**
         * <pre>
         * 消费消息
         *
         * 1/ 消费前后钩子函数
         * 2/ 记录消费开始时间   (为了判断消费是否超时)
         * 3/ 消费消息 {@link MessageListenerConcurrently#consumeMessage}
         * 4/ 记录消费状态  (不重要)
         * 5/ 处理消费结果: {@link #processConsumeResult}
         *
         * </pre>
         */
        @Override
        public void run() {
            if (this.processQueue.isDropped()) {
                log.info("the message queue not be able to consume, because it's dropped. group={} {}", consumerGroup, this.messageQueue);
                return;
            }
            ConsumeMessageContext consumeMessageContext = null;
            ConsumeConcurrentlyContext context = new ConsumeConcurrentlyContext(messageQueue);

            // 设置重试topic名称
            defaultMQPushConsumerImpl.resetRetryAndNamespace(msgs, defaultMQPushConsumer.getConsumerGroup());

            // 钩子函数 before
            if (defaultMQPushConsumerImpl.hasHook()) {
                consumeMessageContext = new ConsumeMessageContext();
                consumeMessageContext.setNamespace(defaultMQPushConsumer.getNamespace());
                consumeMessageContext.setConsumerGroup(defaultMQPushConsumer.getConsumerGroup());
                consumeMessageContext.setProps(new HashMap<String, String>());
                consumeMessageContext.setMq(messageQueue);
                consumeMessageContext.setMsgList(msgs);
                consumeMessageContext.setSuccess(false);
                defaultMQPushConsumerImpl.executeHookBefore(consumeMessageContext);
            }

            long beginTimestamp = System.currentTimeMillis();
            boolean hasException = false;
            ConsumeReturnType returnType = ConsumeReturnType.SUCCESS;
            ConsumeConcurrentlyStatus status = null;
            try {
                if (msgs != null && !msgs.isEmpty()) {
                    for (MessageExt msg : msgs) {
                        // 设置开始消费时间戳
                        MessageAccessor.setConsumeStartTimeStamp(msg, String.valueOf(System.currentTimeMillis()));
                    }
                }
                // note:监听器,消费消息.(开发者自己实现此接口)
                status = messageListener.consumeMessage(Collections.unmodifiableList(msgs), context);
            } catch (Throwable e) {
                log.warn(String.format("consumeMessage exception: %s Group: %s Msgs: %s MQ: %s", RemotingHelper.exceptionSimpleDesc(e), consumerGroup, msgs, messageQueue), e);
                hasException = true;
            }

            // 消费耗时
            long consumeRT = System.currentTimeMillis() - beginTimestamp;
            if (status == null) {
                if (hasException) {
                    returnType = ConsumeReturnType.EXCEPTION;
                } else {
                    returnType = ConsumeReturnType.RETURNNULL;
                }
            } else if (consumeRT >= defaultMQPushConsumer.getConsumeTimeout() * 60 * 1000) {
                returnType = ConsumeReturnType.TIME_OUT;
            } else if (ConsumeConcurrentlyStatus.RECONSUME_LATER == status) {
                returnType = ConsumeReturnType.FAILED;
            } else if (ConsumeConcurrentlyStatus.CONSUME_SUCCESS == status) {
                returnType = ConsumeReturnType.SUCCESS;
            }

            if (defaultMQPushConsumerImpl.hasHook()) {
                consumeMessageContext.getProps().put(MixAll.CONSUME_CONTEXT_TYPE, returnType.name());
            }

            if (status == null) {
                log.warn("consumeMessage return null, Group: {} Msgs: {} MQ: {}", consumerGroup, msgs, messageQueue);
                status = ConsumeConcurrentlyStatus.RECONSUME_LATER;
            }

            // 钩子函数  after
            if (defaultMQPushConsumerImpl.hasHook()) {
                consumeMessageContext.setStatus(status.toString());
                consumeMessageContext.setSuccess(ConsumeConcurrentlyStatus.CONSUME_SUCCESS == status);
                defaultMQPushConsumerImpl.executeHookAfter(consumeMessageContext);
            }

            // 记录消费状态
            getConsumerStatsManager().incConsumeRT(consumerGroup, messageQueue.getTopic(), consumeRT);

            // note:处理消费结果
            //  执行业务消息消费后,在'处理结果'前再次验证一下ProcessQueue的isDroped状态值,如果设置为true,将不对结果进行处理.
            //  也就是说如果在消息消费过程中,在进入run方法之后会校验isDroped,如果由于由新的消费者加入或原先的消费者出现启机,
            //  导致原先分给消费者的队列在负载之后分配给别的消费者,那么在应用程序的角度来看的话,消息会被重复消费。
            if (!processQueue.isDropped()) {
                processConsumeResult(status, context, this);
            } else {
                log.warn("processQueue is dropped without process consume result. messageQueue={}, msgs={}", messageQueue, msgs);
            }
        }

        public MessageQueue getMessageQueue() {
            return messageQueue;
        }

    }
}
